const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const adminSchema = mongoose.Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
      trim: true,
    },
    password: {
      type: String,
      required: true,
      trim: true,
      private: true, // 在JSON转换过程中不包含此字段
    },
    name: {
      type: String,
      required: true,
      trim: true,
    },
    role: {
      type: String,
      enum: ['超级管理员', '内容管理员', '用户管理员'],
      default: '超级管理员',
    },
    permissions: {
      type: [String],
      default: ['manageUsers', 'manageContent', 'manageSystem', 'all'],
    },
    isActive: {
      type: Boolean,
      default: true,
    },
    avatar: {
      type: String,
      trim: true,
      default: ''
    }
  },
  {
    timestamps: true,
  }
);

// 排除私有字段
adminSchema.methods.toJSON = function () {
  const admin = this;
  const adminObject = admin.toObject();

  delete adminObject.password;

  return adminObject;
};

/**
 * 检查用户名是否已被使用
 * @param {string} username - 用户名
 * @param {ObjectId} [excludeAdminId] - 排除的管理员ID
 * @returns {Promise<boolean>}
 */
adminSchema.statics.isUsernameTaken = async function (username, excludeAdminId) {
  const admin = await this.findOne({ username, _id: { $ne: excludeAdminId } });
  return !!admin;
};

/**
 * 验证密码是否匹配
 * @param {string} password - 密码
 * @returns {Promise<boolean>}
 */
adminSchema.methods.isPasswordMatch = async function (password) {
  const admin = this;
  return bcrypt.compare(password, admin.password);
};

// 保存前加密密码
adminSchema.pre('save', async function (next) {
  const admin = this;
  if (admin.isModified('password')) {
    admin.password = await bcrypt.hash(admin.password, 8);
  }
  next();
});

/**
 * @typedef Admin
 */
const Admin = mongoose.model('Admin', adminSchema, 'admin_users');

module.exports = Admin; 